<template>
  <el-dialog
    title="课程教学总结详情"
    v-model="dialogVisible"
    width="70%"
    :before-close="handleClose"
    class="summary-dialog"
  >
    <div class="kcjxzj-view" v-loading="loading">
      <el-card class="summary-card">
        <template #header>
          <div class="card-header">
            <span>总结基本信息</span>
            <div v-if="summary">
              <el-tag :type="getStatusType(summary.statusName || getStatusText(summary.statusId))">{{ summary.statusName || getStatusText(summary.statusId) }}</el-tag>
            </div>
          </div>
        </template>
        
        <div v-if="summary" class="summary-info">
          <!-- 使用与编辑页面相同的基本信息组件，但设为只读模式 -->
          <SummaryBasicInfo
            :model-value="summaryFormData"
            :courses="courses"
            :terms="terms"
            :departments="departments"
            :teaching-missions="teachingMissions"
            :is-readonly="true"
            :current-mission-id="null"
          />
          
          <!-- 其他详细信息 -->
          <el-descriptions :column="2" border style="margin-top: 20px;">
            <el-descriptions-item label="创建时间">
              <el-tag size="small" type="info" effect="plain">{{ formatDate(summary.createDate) }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="提交时间">
              <el-tag size="small" type="success" effect="plain" v-if="getLatestSubmitTime()">{{ formatDate(getLatestSubmitTime()) }}</el-tag>
              <el-tag size="small" type="warning" effect="plain" v-else>尚未提交</el-tag>
            </el-descriptions-item>
          </el-descriptions>
          
          <!-- 成绩统计信息 -->
          <div v-if="summary.teachingMissionIds && summary.teachingMissionIds.length > 0" class="score-statistics-section">
            <ScoreStatistics :teaching-mission-ids="summary.teachingMissionIds" />
          </div>
          
          <div class="summary-content">
            <h3>总结内容</h3>
            <div class="content-box">
              <h4>教学设计与实施</h4>
              <RichTextViewer v-if="summary.designAndImplementation" :content="summary.designAndImplementation" />
              <p v-else class="empty-content">暂无教学设计与实施内容</p>
              
              <h4>考试考核</h4>
              <RichTextViewer v-if="summary.assessment" :content="summary.assessment" />
              <p v-else class="empty-content">暂无考试考核内容</p>
              
              <h4>教学反思与改进</h4>
              <RichTextViewer v-if="summary.reflectionAndImprovement" :content="summary.reflectionAndImprovement" />
              <p v-else class="empty-content">暂无教学反思与改进内容</p>
            </div>
          </div>
        </div>
        
        <div v-else-if="!loading" class="empty-data">
          <el-empty description="未找到相关总结信息"></el-empty>
        </div>
      </el-card>
      
      <!-- 审核流程时间线 -->
      <el-card v-if="summary && canViewAuditInfo()" class="timeline-card">
        <template #header>
          <div class="card-header">
            <span>审核流程时间线</span>
          </div>
        </template>
        
        <AuditTimeline
          :submit-info="{
            submitterName: summary.teacherName,
            submitTime: summary.commitDate,
            description: '提交课程教学总结'
          }"
          :research-audit="researchAudit"
          :department-audit="departmentAudit"
          :current-status="summary.statusId"
        />
      </el-card>
    </div>
  </el-dialog>
</template>

<script>
import { ref, watch, onMounted, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { getKcjxzjById, getAuditHistory } from '@/api/course-teaching-summary';
import { departmentApi, courseApi, termApi } from '@/api/base-data';
import { teachingMissionApi } from '@/api/teaching-mission';
import { useUserStore } from '@/stores/user';
import AuditTimeline from './AuditTimeline.vue';
import ScoreStatistics from '../summary/ScoreStatistics.vue';
import RichTextViewer from './RichTextViewer.vue';
import SummaryBasicInfo from '../summary/SummaryBasicInfo.vue';

export default {
  components: {
    AuditTimeline,
    ScoreStatistics,
    RichTextViewer,
    SummaryBasicInfo
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    summaryId: {
      type: [String, Number],
      default: null
    }
  },
  emits: ['update:visible', 'close'],
  setup(props, { emit }) {
    const userStore = useUserStore();
    const dialogVisible = ref(props.visible);
    const summary = ref(null);
    const loading = ref(false);
    const courses = ref([]);
    const terms = ref([]);
    const departments = ref([]);
    const teachingMissions = ref([]);
    const auditHistory = ref([]);
    const researchAudit = ref(null);
    const departmentAudit = ref(null);

    // 将总结数据转换为表单数据格式，供 SummaryBasicInfo 组件使用
    const summaryFormData = computed(() => {
      if (!summary.value) {
        return {
          courseId: null,
          termId: null,
          departmentIds: [],
          textbook: '',
          textbookType: '',
          teachingMissionIds: []
        };
      }
      
      return {
        courseId: summary.value.courseId,
        termId: summary.value.termId,
        departmentIds: summary.value.departmentIds || [],
        textbook: summary.value.textbook || '',
        textbookType: summary.value.textbookType || '',
        teachingMissionIds: summary.value.teachingMissionIds || []
      };
    });

    // 监听对话框显示状态
    watch(() => props.visible, (newVal) => {
      dialogVisible.value = newVal;
      if (newVal && props.summaryId) {
        fetchSummary(props.summaryId);
      }
    });

    // 监听本地对话框状态变化
    watch(dialogVisible, (newVal) => {
      emit('update:visible', newVal);
      if (!newVal) {
        emit('close');
      }
    });

    // 获取总结详情及相关审核信息
    const fetchSummary = async (id) => {
      if (!id) return;
      
      loading.value = true;
      try {
        // 并行请求总结详情和审核历史
        const [summaryData, auditHistoryData] = await Promise.all([
          getKcjxzjById(id),
          getAuditHistory(id)
        ]);
        
        summary.value = summaryData;
        auditHistory.value = auditHistoryData || [];
        
        // 处理审核历史记录，获取最新的教研室和部系审核信息
        if (auditHistory.value && auditHistory.value.length > 0) {
          // 按审核时间排序，最新的在前面
          auditHistory.value.sort((a, b) => new Date(b.auditTime) - new Date(a.auditTime));
          
          // 获取最新的教研室审核记录
          researchAudit.value = auditHistory.value.find(audit => 
            audit.auditLevel === 'RESEARCH_OFFICE'
          );
          
          // 获取最新的部系审核记录
          departmentAudit.value = auditHistory.value.find(audit => 
            audit.auditLevel === 'DEPARTMENT'
          );
        }
      } catch (error) {
        
        // 提供更具体的错误信息
        let errorMsg = '获取总结详情失败';
        if (error.response) {
          // 服务器返回的错误
          if (error.response.status === 404) {
            errorMsg = '找不到指定的总结记录';
          } else if (error.response.status === 403) {
            errorMsg = '您没有权限查看此总结';
          } else if (error.response.data && error.response.data.message) {
            errorMsg = error.response.data.message;
          }
        }
        
        ElMessage.error(errorMsg);
        // 出错时也关闭对话框
        handleClose();
      } finally {
        loading.value = false;
      }
    };
    
    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '-';
      
      try {
        // 尝试创建日期对象
        const date = new Date(dateString);
        
        // 检查日期是否有效
        if (isNaN(date.getTime())) {
          return dateString; // 如果无法解析，返回原始字符串
        }
        
        // 格式化日期
        return date.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        });
      } catch (error) {
        return dateString; // 出错时返回原始字符串
      }
    };
    
    // 获取状态类型样式
    const getStatusType = (status) => {
      // Element Plus的Tag组件仅支持以下type值: "primary", "success", "warning", "info", "danger"
      const statusMap = {
        '草稿': 'info',
        '未提交': 'info',
        '待审核': 'warning', 
        '已通过': 'success',
        '已教研室审核通过': 'success',
        '已部系审核通过': 'success',
        '教研室审核未通过': 'danger',
        '部系审核未通过': 'danger'
      };
      return statusMap[status] || 'info';
    };

    // 关闭对话框
    const handleClose = () => {
      dialogVisible.value = false;
      // 重置状态，避免数据残留
      summary.value = null;
      researchAudit.value = null;
      departmentAudit.value = null;
      auditHistory.value = [];
    };

    // 在组件加载时获取必要的数据
    onMounted(async () => {
      try {
        // 获取课程、学期、教学任务和部门数据
        const [coursesData, termsData, missionsData, departmentsData] = await Promise.all([
          courseApi.getAllCourses(),
          termApi.getAllTerms(),
          teachingMissionApi.getAllTeachingMissionsList(),
          departmentApi.getAllDepartments()
        ]);
        
        courses.value = coursesData || [];
        terms.value = termsData || [];
        // 处理教学任务数据
        teachingMissions.value = Array.isArray(missionsData) ? missionsData : (missionsData?.content || missionsData?.data || []);
        departments.value = departmentsData || [];
        
      } catch (error) {
        // 如果权限错误，尝试使用权限受限的API
        if (error.response && error.response.status === 403) {
          try {
            const missionsData = await teachingMissionApi.getMyTeachingMissions();
            teachingMissions.value = (missionsData && missionsData.content) ? missionsData.content : (missionsData || []);
          } catch (fallbackError) {
            ElMessage.warning('权限不足，部分信息可能无法完整显示');
          }
        } else {
          ElMessage.warning('权限不足，部分信息可能无法完整显示');
        }
      }
    });

    // 根据部门名称列表或ID列表获取部门名称列表
    const getDepartmentNames = (departmentNamesOrIds) => {
      if (!departmentNamesOrIds || !departmentNamesOrIds.length) return '-';
      
      // 如果传入的是字符串数组，直接返回连接结果
      if (Array.isArray(departmentNamesOrIds) && typeof departmentNamesOrIds[0] === 'string') {
        return departmentNamesOrIds.join(', ');
      }
      
      // 如果传入的是ID数组，则需要查找对应的部门名称
      try {
        let idArray = departmentNamesOrIds;
        if (typeof departmentNamesOrIds === 'string') {
          idArray = departmentNamesOrIds.split(',').map(id => id.trim());
        }
        
        // 确保departments已加载
        if (!departments.value || departments.value.length === 0) {
          return '正在加载部门信息...';
        }
        
        const deptNames = idArray
          .map(id => {
            const numericId = Number(id);
            const dept = departments.value.find(d => 
              d.id === id || 
              d.id === numericId || 
              String(d.id) === String(id)
            );
            return dept ? dept.name : `部门${id}`;
          })
          .filter(name => name)
          .join(', ');
        
        return deptNames || '-';
      } catch (error) {
        return '-';
      }
    };
    
    // 获取教学任务名称
    const getTeachingMissionNames = (missionIds) => {
      if (!missionIds || !missionIds.length) return '-';
      
      try {
        // 处理可能的字符串输入（如 "1,2,3"）
        let idArray = missionIds;
        if (typeof missionIds === 'string') {
          idArray = missionIds.split(',').map(id => id.trim());
        }
        
        // 确保教学任务数据已加载
        if (!teachingMissions.value || teachingMissions.value.length === 0) {
          return '正在加载教学任务信息...';
        }
        
        // 根据ID查找教学任务名称
        const missionNames = idArray.map(id => {
          // 尝试不同格式的ID进行匹配
          const numericId = Number(id);
          const mission = teachingMissions.value.find(m => 
            m.id === id || 
            m.id === numericId || 
            String(m.id) === String(id)
          );
          
          if (mission) {
            let name = '';
            // 根据TeachingMissionDTO结构获取属性
            const courseName = mission.courseName || '';
            const termName = mission.termName || '';
            const courseCode = mission.courseCode || '';
            
            // 优先显示课程名称和学期的组合
            if (courseName && termName) {
              name = `${courseName}(${termName})`;
            } else if (courseName) {
              name = courseName;
            } else if (termName) {
              name = `学期: ${termName}`;
            } else if (courseCode) {
              name = `课程代码: ${courseCode}`;
            } else if (mission.id) {
              name = `教学任务 ${mission.id}`;
            } else {
              name = `任务${id}`;
            }
            
            return name;
          }
          
          return `教学任务${id}`;
        });
        
        return missionNames.join(', ') || '-';
      } catch (error) {
        return '-';
      }
    };
    
    // 根据ID获取教师名称 - 简化版，优先使用summary中的教师名称
    const getTeacherNameById = (teacherId) => {
      if (!teacherId) return '-';
      // 优先使用summary对象中的教师名称，如果没有则显示ID
      return summary.value?.teacherName || `教师${teacherId}`;
    };

    // 获取状态文本（备用方法，优先使用summary.statusName）
    const getStatusText = (statusId) => {
      const statusMap = {
        1: '未提交',
        2: '已提交',
        3: '已教研室审核通过',
        4: '已部系审核通过',
        5: '教研室审核未通过',
        6: '部系审核未通过'
      };
      return statusMap[statusId] || '-';
    };

    // 检查是否有权限查看审核信息
    const canViewAuditInfo = () => {
      // 管理员和部门负责人可以查看所有审核信息
      if (userStore.isAdmin || userStore.isDepartmentHead || userStore.isResearchHead) {
        return true;
      }
      
      // 普通教师只能查看自己的课程教学总结的审核信息
      if (userStore.isTeacher && summary.value) {
        return summary.value.teacherId === parseInt(userStore.userId);
      }
      
      return false;
    };

    // 检查是否可以查看具体的审核人信息
    const canViewAuditorDetails = () => {
      // 管理员和各级负责人可以查看审核人详细信息
      return userStore.isAdmin || userStore.isDepartmentHead || userStore.isResearchHead;
    };

    // 获取教材类别名称
    const getTextbookTypeName = (typeId) => {
      const typeMap = {
        '1': '统编教材',
        '2': '自编教材', 
        '3': '其他教材',
        1: '统编教材',
        2: '自编教材',
        3: '其他教材'
      };
      return typeMap[typeId] || typeId || '-';
    };

    // 获取最近一次提交时间
    const getLatestSubmitTime = () => {
      if (!summary.value) return null;
      
      // 优先使用 commitDate（提交时间）
      if (summary.value.commitDate) {
        return summary.value.commitDate;
      }
      
      // 如果没有 commitDate，检查审核历史中的提交时间
      if (auditHistory.value && auditHistory.value.length > 0) {
        // 查找最早的审核记录（即首次提交时间）
        const sortedAudits = [...auditHistory.value].sort((a, b) => 
          new Date(a.auditTime) - new Date(b.auditTime)
        );
        
        if (sortedAudits.length > 0) {
          return sortedAudits[0].auditTime;
        }
      }
      
      // 最后尝试使用 submitDate 或 submittedTime 字段（如果存在）
      if (summary.value.submitDate) {
        return summary.value.submitDate;
      }
      
      if (summary.value.submittedTime) {
        return summary.value.submittedTime;
      }
      
      // 如果状态不是草稿状态（statusId > 1），但没有明确的提交时间，使用创建时间作为估算
      if (summary.value.statusId && summary.value.statusId > 1 && summary.value.createDate) {
        return summary.value.createDate;
      }
      
      return null;
    };

    return {
      dialogVisible,
      summary,
      loading,
      courses,
      terms,
      departments,
      teachingMissions,
      summaryFormData,
      auditHistory,
      researchAudit,
      departmentAudit,
      formatDate,
      getStatusType,
      getStatusText,
      getDepartmentNames,
      getTeachingMissionNames,
      canViewAuditInfo,
      canViewAuditorDetails,
      getTextbookTypeName,
      getLatestSubmitTime,
      userStore,
      handleClose
    };
  }
};
</script>

<style scoped>
.summary-dialog {
  display: flex;
  flex-direction: column;
}

/* 自定义对话框样式 */
:deep(.el-dialog) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-dialog__header) {
  background-color: #f5f7fa;
  padding: 15px 20px;
  margin: 0;
  border-bottom: 1px solid #e4e7ed;
}

:deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

:deep(.el-dialog__headerbtn) {
  top: 15px;
}

:deep(.el-dialog__body) {
  padding: 20px;
  max-height: 70vh;
  overflow-y: auto;
}

.kcjxzj-view {
  padding: 0;
}

.summary-card,
.audit-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header span {
  font-size: 16px;
  font-weight: 600;
}

.summary-info {
  margin-bottom: 20px;
}

.summary-content {
  margin-top: 20px;
}

.score-statistics-section {
  margin-top: 20px;
  margin-bottom: 20px;
  border-top: 1px solid #ebeef5;
  padding-top: 20px;
}

.summary-content h3 {
  font-size: 16px;
  margin-bottom: 10px;
  font-weight: 600;
  color: #303133;
}

.content-box {
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
  min-height: 100px;
  white-space: pre-wrap;
  line-height: 1.6;
}

.content-box h4 {
  font-size: 15px;
  font-weight: 600;
  color: #409EFF;
  margin-top: 12px;
  margin-bottom: 8px;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 6px;
}

.content-box h4:first-child {
  margin-top: 0;
}

.content-box p {
  margin-bottom: 10px;
  padding-left: 8px;
}

/* 富文本查看器在内容框中的样式 */
.content-box :deep(.rich-text-viewer) {
  background-color: transparent;
  border: none;
  padding: 0 8px;
  margin-bottom: 10px;
  min-height: 60px;
}

.empty-data {
  padding: 40px 0;
  text-align: center;
}

.empty-content {
  color: #909399;
  font-style: italic;
}

.empty-text {
  color: #909399;
  font-size: 13px;
  font-style: italic;
}

.audit-info-block {
  padding: 10px 0;
}

.audit-detail-row {
  display: flex;
  align-items: flex-start;
  margin-bottom: 8px;
}

.audit-detail-row:last-child {
  margin-bottom: 0;
}

.audit-label {
  display: inline-block;
  width: 80px;
  font-weight: 500;
  color: #606266;
  flex-shrink: 0;
}

.audit-comments {
  flex: 1;
  word-break: break-word;
  line-height: 1.4;
  color: #303133;
}

.timeline-card {
  margin-top: 20px;
}

.timeline-card .card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
